<template>
	<el-dialog v-model="isShowDialog" title="编辑数据应用原型" width="80%" center>
		<el-tabs v-model="activeName">
			<el-tab-pane label="基本信息" name="basic">
				<BasicInfoForm ref="basicInfoRef" :info="info" />
			</el-tab-pane>
			<el-tab-pane label="字段信息" name="cloum">
				<div><el-button type="primary" @click="submitSync">同步数据表</el-button></div>
				<el-radio-group v-model="info.pkFieldName">
					<el-table ref="dragTable" :data="columns" row-key="columnId" height="450px">
						<el-table-column label="字段序号" prop="sort" :show-overflow-tooltip="true">
							<template #default="scope">
								<el-input v-model="scope.row.sort" @blur="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="字段列名" prop="columnName" width="150" :show-overflow-tooltip="true">
							<template #default="scope">
								<el-input v-model="scope.row.columnName" @blur="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column fixed="left" label="字段描述" width="150">
							<template #default="scope">
								<el-input v-model="scope.row.columnComment" @blur="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="存储类型" prop="columnType" width="120" :show-overflow-tooltip="true" />
						<el-table-column label="数据别名" width="150">
							<template #default="scope">
								<el-input v-model="scope.row.fieldName" @blur="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="主键" width="50">
							<template #default="scope">
								<el-radio :value="scope.row.fieldName" :true-value="1" :false-label="0"
									@change="handlePrimaryChange(scope)" />
							</template>
						</el-table-column>

						<el-table-column label="插入" width="50">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isInsert" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="编辑" width="50" :cell-style="{ 'text-align': 'center' }">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isEdit" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="列表" width="50" :cell-style="{ 'text-align': 'center' }">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isList" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="查询" width="50" :cell-style="{ 'text-align': 'center' }">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isQuery" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="可见" width="50" :cell-style="{ 'text-align': 'center' }">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isShow" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="必填" width="50">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isRequired" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="索引" width="50">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isIndex" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="去重" width="50">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isDistinct" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="分组" width="50">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isGroup" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="排序" width="50">
							<template #default="scope">
								<el-checkbox v-model="scope.row.isSort" :true-value="1" :false-label="0"
									@change="handleColChange(scope)" />
							</template>
						</el-table-column>
						<el-table-column label="匹配规则" width="120">
							<template #default="scope">
								<el-select v-model="scope.row.queryType" @change="handleColChange(scope)">
									<el-option label="等同" value="EQ" />
									<el-option label="不同" value="NE" />
									<el-option label="大于" value="GT" />
									<el-option label="大等" value="GTE" />
									<el-option label="小于" value="LT" />
									<el-option label="小等" value="LTE" />
									<el-option label="具有" value="LIKE" />
									<el-option label="没有" value="NL" />
									<el-option label="包含" value="IN" />
									<el-option label="不含" value="NI" />
									<el-option label="区间" value="BT" />
									<el-option label="空值" value="NAN" />
									<el-option label="非空" value="VAL" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="前置数值" width="150">
							<template #default="scope">
								<el-input :disabled="scope.row.queryType == 'NaN' || scope.row.queryType == 'VAL'"
									v-model="scope.row.searchValue" @blur="handleColChange(scope)"
									placeHolder="检索固定值" />
							</template>
						</el-table-column>
						<el-table-column label="默认数据" width="150">
							<template #default="scope">
								<el-input v-model="scope.row.defaultValue" @blur="handleColChange(scope)"
									placeHolder="新增默认值" />
							</template>
						</el-table-column>
						<el-table-column label="显示控件" width="140">
							<template #default="scope">
								<el-select v-model="scope.row.htmlType" @change="handleColChange(scope)">
									<el-option label="文本框" value="input" />
									<el-option label="下拉框" value="select" />
									<el-option label="开关" value="switch" />
									<el-option label="单选框" value="radio" />
									<el-option label="多选框" value="checkbox" />
									<el-option label="文件选择" value="file" />
									<el-option label="文本域" value="textarea" />
									<el-option label="日期控件" value="datetime" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="控件宽度" width="150">
							<template #default="scope">
								<el-input v-model="scope.row.htmlWidth" @blur="handleColChange(scope)"
									placeHolder="默认自适应" />
							</template>
						</el-table-column>
						<el-table-column label="数据汇聚" width="120">
							<template #default="scope">
								<!-- 运算规则 0 SUM 1 COUNT 2 AVG 3 MAX 4 MIN 5 VARIANCE 6 STDDEV 7 GROUP_CONCAT -->
								<el-select v-model="scope.row.calcType" @change="handleColChange(scope)">
									<el-option label="无" value="NULL" />
									<el-option label="汇总" value="0" />
									<el-option label="计数" value="1" />
									<el-option label="平均值" value="2" />
									<el-option label="最大值" value="3" />
									<el-option label="最小值" value="4" />
									<el-option label="方差" value="5" />
									<el-option label="标准差" value="6" />
									<el-option label="分组拼接" value="7" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="关联字典" width="160">
							<template #default="scope">
								<el-select v-model="scope.row.dictType" clearable filterable placeholder="请选择"
									@change="handleColChange(scope)">
									<el-option v-for="dict in dictOptions" :key="dict.dictType" :label="dict.dictName"
										:value="dict.dictType">
										<span style="float: left">{{ dict.dictName }}</span>
										<span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType
											}}</span>
									</el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="关联表单" width="160">
							<template #default="scope">
								<el-select v-model="scope.row.linkTableName" clearable filterable placeholder="请选择"
									@change="handleColChange(scope, 'linkTable')">
									<el-option v-for="table in tableTree" :key="table.tableId" :label="table.tableName"
										:value="table.tableId">
										<span style="float: left">{{ table.tableName }}</span>
										<span style="float: right; color: #8492a6; font-size: 13px">{{ table.className
										}}</span>
									</el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="关联字段" width="160">
							<template #default="scope">
								<el-select v-model="scope.row.linkColumnName" clearable filterable placeholder="请选择"
									@visible-change="handleSelect(scope)" @change="handleColChange(scope)">
									<el-option v-for="col in linkCol" :key="col.columnName" :label="col.columnName"
										:value="col.columnName">
										<span style="float: left">{{ col.columnName }}</span>
										<span style="float: right; color: #8492a6; font-size: 13px">{{ col.columnComment
										}}</span>
									</el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="映射字段" width="160">
							<template #default="scope">
								<el-select v-model="scope.row.linkBindField" clearable filterable placeholder="请选择"
									@change="handleColChange(scope)">
									<el-option v-for="col in columns" :key="col.columnName" :label="col.columnName"
										:value="col.columnName">
										<span style="float: left">{{ col.columnName }}</span>
										<span style="float: right; color: #8492a6; font-size: 13px">{{ col.columnComment
										}}</span>
									</el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="关联类型" width="120">
							<template #default="scope">
								<el-select v-model="scope.row.linkSyncType" @change="handleColChange(scope)">
									<el-option label="独立" :value="0" />
									<el-option label="拉取" :value="1" />
									<el-option label="推送" :value="2" />
									<el-option label="同步" :value="3" />
								</el-select>
							</template>
						</el-table-column>
					</el-table>
				</el-radio-group>
			</el-tab-pane>
			<el-tab-pane label="接口钩子" name="hook">
				<HookInfoForm :info="info" />
			</el-tab-pane>
			<el-tab-pane label="表单权限表" name="aclTable">
				<AclTable :curApiId="curApiId" />
			</el-tab-pane>
			<el-tab-pane label="数据权限表" name="aclData">
				<AclData :curApiId="curApiId" />
			</el-tab-pane>
		</el-tabs>
		<template #footer> </template>
	</el-dialog>
</template>
<script>
import { ref, toRefs, getCurrentInstance, reactive } from 'vue';
import { updateTable, getTableTree, updateBasicTable, getTableColInfo, getTableBasicInfo, snycTable } from '@/api/gen/table';
import { listType as getDictOptionselect } from '@/api/system/dict/type';

import BasicInfoForm from './basicInfoForm.vue';
import HookInfoForm from './hookInfoForm.vue';
import AclTable from './aclTable.vue';
import AclData from './aclData.vue';
import { ElMessage } from 'element-plus';

export default {
	name: 'genEdit',
	components: {
		BasicInfoForm,
		HookInfoForm,
		AclTable,
		AclData,
	},
	setup() {
		const { proxy } = getCurrentInstance();
		const basicInfoRef = ref();
		const state = reactive({
			// 是否显示弹出层
			isShowDialog: false,
			loading: false,
			// 选中选项卡的 name
			activeName: 'cloum',
			// 表列信息
			columns: [],
			tableTree: [],
			// 字典信息
			dictOptions: [],
			// 表详细信息
			info: {},
			// 当前点击的apiId
			curApiId: '',
			linkCol: [],
			primary: false,
		});

		// watch(
		// 	() => state.info,
		// 	(newVal, oldVal) => {
		// 		console.log('新值:', newVal);
		// 		console.log('旧值:', oldVal);
		// 		// 在这里可以执行其他逻辑操作
		// 	},
		// 	{ deep: true }
		// );

		// 比较两个对象的 sort 属性
		const compareSorts = (a, b) => {
			// 如果 sort 属性为 null，则将其视为无穷大
			if (a.sort === null || b.sort === null) {
				return 0; // 不参与排序
			}
			// 比较 sort 属性
			return a.sort - b.sort;
		};

		// 打开弹窗
		const openDialog = (row) => {
			// state.isShowDialog = true;
			if (row.tableId) {
				state.curApiId = row.tableId;
				// 获取表详细信息
				getTableColInfo(row.tableId).then((res) => {
					let columns = res.data
					// let columns = res.data.filter((item) => {
					// 	return !['createTime', 'update_time', 'delete_time'].includes(item.columnName);
					// });
					const colArr = columns.map((item) => {
						return {
							...item,
						};
					});
					state.isShowDialog = true;
					colArr.sort(compareSorts);
					state.columns = colArr;
				});
				getTableBasicInfo(row.tableId).then((res) => {
					state.info = res.data;
					state.isShowDialog = true;
				});

				state.loading = false;
				/** 查询字典下拉列表 */
				getDictOptionselect({ pageNum: 1, pageSize: 100 }).then((response) => {
					state.dictOptions = response.data.data;
				});
				getTableTree().then((response) => {
					state.tableTree = response.data.map((item) => {
						return { ...item, tableId: item.tableId.toString() };
					});
					// if (state.tableTree.length === 0) {
					state.tableTree.unshift({ tableId: '0', tableName: '请选择' });
					// }
				});
			}
		};

		/** 选择主键 */
		const handlePrimaryChange = (column) => {
			updateBasicTable({ ...state.info, pkColumn: column.row.columnName, pkFieldName: column.row.fieldName }).then((res) => { });
		}

		/** 提交按钮 */
		const submitForm = () => {
			const basicForm = basicInfoRef.value.basicInfoForm;
			Promise.all([basicForm].map(getFormPromise)).then((res) => {
				const validateResult = res.every((item) => !!item);
				if (validateResult) {
					const genTable = Object.assign({}, basicInfoRef.value.info);
					delete genTable.columns;
					// genTable.columns = state.columns;
					state.loading = true;
					// const basicApi = updateBasicTable(genTable);
					// updateTable(genTable).then((res) => {
					// 	ElMessage.success('修改成功');
					// 	state.loading = false;
					// 	closeDialog();
					// });
					updateBasicTable(genTable).then((res) => {
						ElMessage.success('修改成功');
						state.loading = false;
						closeDialog();
					});
				} else {
					ElMessage.error('表单校验未通过，请重新检查提交内容');
					// return;
				}
			});
		};
		const getTables = () => {
			getTableTree().then((response) => {
				state.tableTree = response.data;
				state.tableTree.unshift({ tableId: 0, className: '请选择' });
			});
		};
		const getTablesCol = (tableName) => {
			return state.tableTree.filter(function (item) {
				if (item.tableName === tableName) {
					return item.columns;
				}
			});
		};
		const getFormPromise = (form) => {
			return new Promise((resolve) => {
				form.validate((res) => {
					resolve(res);
				});
			});
		};
		// 关闭弹窗
		const closeDialog = (row) => {
			proxy.mittBus.emit('onEditTableModule', row);
			state.isShowDialog = false;
		};

		const handleColChange = (scope, sign) => {
			if (sign == "linkTable") {
				const linkTableName = state.tableTree.find(item => item.tableId === scope.row.linkTableName)?.tableName;
				updateTable(scope.row.columnId, {...scope.row, linkTableName}).then((res) => { });
				return
			}
			updateTable(scope.row.columnId, scope.row).then((res) => { });
		};

		// 关联字段下拉框触发
		const handleSelect = (scope) => {
			getTableColInfo(scope.row.linkTableName).then((res) => {
				state.linkCol = res.data;
			});
		};

		// 同步数据表
		const submitSync = () => {
			snycTable(basicInfoRef.value.info.tableId).then((res) => {
				if (res.status == 0) {
					ElMessage.success('同步成功');
					// 获取表详细信息
					getTableColInfo(basicInfoRef.value.info.tableId).then((res) => {
						let columns = res.data.filter((item) => {
							return !['createTime', 'update_time', 'delete_time'].includes(item.columnName);
						});
						state.columns = columns.map((item) => {
							return {
								...item,
							};
						});
					});
				} else {
					ElMessage.error('同步失败');
				}
			});
		};

		return {
			basicInfoRef,
			openDialog,
			closeDialog,
			getTablesCol,
			getTables,
			submitForm,
			getFormPromise,
			handleSelect,
			handleColChange,
			submitSync,
			handlePrimaryChange,
			...toRefs(state),
		};
	},
};
</script>
